﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Xml;

namespace Medianamik.UI.ConfigManagement
{
    /// <summary>
    /// Importer un fichier de ressource
    /// </summary>
    public partial class GlobalRessourcesConfig : Medianamik.UI.BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            btnImport.Click += new EventHandler(btnImport_Click);
            if(!Page.IsPostBack)
                BindFilesList();
        }

        /// <summary>
        /// Obtenir la liste des ressources disponnibles du répertoire "App_GlobalResources"
        /// </summary>
        public void BindFilesList()
        {
            var files = (from file in Directory.GetFiles(Server.MapPath("/App_GlobalResources"), "*.*", SearchOption.TopDirectoryOnly)
                         orderby file ascending
                         select new ResourceFile(
                            file,
                            new FileInfo(file).Name,
                            new FileInfo(file).CreationTime,
                            new FileInfo(file).DirectoryName,
                            false));

            rptFiles.DataSource= files.ToList();
            rptFiles.DataBind();

        }

        /// <summary>
        /// Procéder à l'importation des fichiers de ressources sélectrionnés
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnImport_Click(object sender, EventArgs e)
        {
            foreach (RepeaterItem rptItem in rptFiles.Controls)
            {
                if (rptItem.ItemType == ListItemType.Item || rptItem.ItemType == ListItemType.AlternatingItem)
                {
                    CheckBox chkFile = (CheckBox)Medianamik.UI.Utility.FindControlRecursive(rptItem, "chkFile");
                    if (chkFile.Checked)
                        if (ImportRessourceFile(chkFile.Text))
                            ((Label)Medianamik.UI.Utility.FindControlRecursive(rptItem, "lblStatus")).Text = Resources("ConfigManagement", "GlobalRessourcesConfig_lblStatusOK");
                        else
                            ((Label)Medianamik.UI.Utility.FindControlRecursive(rptItem, "lblStatus")).Text = Resources("ConfigManagement", "GlobalRessourcesConfig_lblStatusERROR");
                }
            }
        }

        /// <summary>
        /// Importer les données du fichier de ressources dans la base de données
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private bool ImportRessourceFile(string fileName)
        {
            bool success = true;
            //Obtenir les infos sur la culture et sur la clé primaire
            string[] fileParts = fileName.Split('.');
            string culture="", resourceType="";
            switch(fileParts[fileParts.Length-2].ToLower())
            {
                case "fr-fr":
                    culture = "fr-CA";
                    resourceType = fileName.Replace(".fr-FR.resx", "");
                    break;
                case "en-ca":
                    culture = "en-ca";
                    resourceType = fileName.Replace(".en-CA.resx","");
                    break;
                default:
                    success = false;
                    break;
            }

            if (success)
            {
                //Obtenir le XML du document
                string xml = File.ReadAllText(Server.MapPath(String.Format("/App_GlobalResources/{0}", fileName)));
                XmlDocument resDoc = new XmlDocument();
                resDoc.LoadXml(xml);

                //Obtenir les clés de ressources
                XmlNodeList nodes = resDoc.SelectNodes("/root/data");
                Medianamik.Globalization.TranslationResourcesDAL trans = new Medianamik.Globalization.TranslationResourcesDAL(resourceType);
                foreach (XmlNode node in nodes)
                    trans.CreateResource(node.Attributes["name"].Value, culture, node.ChildNodes[1].FirstChild.Value);
            }

            return success;
        }
    }
    
    /// <summary>
    /// Map d'un fichier 
    /// </summary>
    public class ResourceFile
    {

        public string Path { get; set; }
        public string Name { get; set; }
        public DateTime CreationDate { get; set; }
        public string DirectoryName { get; set; }
        public bool IsDirectory { get; set; }

        public ResourceFile(string pPath, string pName, DateTime pCreationDate, string pDirectoryName, bool pIsDirectory)
        {
            Path = pPath;
            Name = pName;
            CreationDate = pCreationDate;
            DirectoryName = pDirectoryName;
            IsDirectory = pIsDirectory;
        }


    }
}
